#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by chy on 2017/4/12 15:55
"""
http://docs.gunicorn.org/en/latest/settings.html#settings

useage:gunicorn -c ./config.guni -b 0.0.0.0:80  app_package:app_name

"""
#-b can instead by special this line
#bind = "0.0.0.0:80"

#or use the code but you take attention for ConfigBean file
#import _utils.Identification
#from _utils.ConfigBean import ConfigBean as _Cfg
#bind = "%s:%s" % (str(_utils.Identification._getLocalLanIp()),_Cfg().http_server.port)


import os
chdir = os.path.dirname(os.path.realpath(__file__))
import sys
sys.path.append(chdir)

import multiprocessing
workers = multiprocessing.cpu_count() / 2 + 1
worker_class = "gevent"
limit_request_field_size = 0

# access-logfile
import os
strLogDir = chdir + '/log'
if not os.path.isdir(strLogDir):
    os.mkdir(strLogDir)
strLogDir += "/gunicorn"
if not os.path.isdir(strLogDir):
    os.mkdir(strLogDir)
accesslog = strLogDir + "/access.log"
loglevel = "info"
access_log_format = '%(t)s %(h)s %(l)s %(u)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'

# logger_class
import logging
from gunicorn.glogging import Logger as GLOG
from gunicorn import util
import time
class GunicornLogForMidNight(GLOG):
    def __init__(self, cfg):
        super(GunicornLogForMidNight, self).__init__(cfg)

    def now(self):
        """ return date in Apache Common Log Format """
        return time.strftime('[%Y-%m-%d %H:%M:%S %z]')

    def _set_handler(self, log, output, fmt, stream=None):
        # remove previous gunicorn log handler
        h = self._get_gunicorn_handler(log)
        if h:
            log.handlers.remove(h)

        if output is not None:
            if output == "-":
                h = logging.StreamHandler(stream)
            else:
                util.check_is_writeable(output)
                h = logging.handlers.TimedRotatingFileHandler(output, 'MIDNIGHT')
                # make sure the user can reopen the file
                try:
                    os.chown(h.baseFilename, self.cfg.user, self.cfg.group)
                except OSError:
                    # it's probably OK there, we assume the user has given
                    # /dev/null as a parameter.
                    pass

            h.setFormatter(fmt)
            h._gunicorn = True
            log.addHandler(h)

logger_class = GunicornLogForMidNight
